package Meter::Action::Login;

#===============================================================================
#     REVISION:  $Id: Login.pm 172 2013-02-26 10:19:53Z xdr.box@gmail.com $
#  DESCRIPTION:  Login action
#===============================================================================

use strict;
use warnings;

use Readonly;
Readonly our $VERSION => qw($Revision: 172 $) [1];

use English qw( -no_match_vars );

#use Smart::Comments;

use Meter::Log;
use Meter::Utils qw(
    generate_session_id
);

use Meter::Users;
use Meter::Sessions;

use base qw(Meter::Action);

sub is_auth_requied {
    my $self = shift;

    return 0;
}

sub generate_page_content {
    my $self = shift;

    my $logger = get_logger();

    if ( $self->is_user_logged_in() ) {
        $logger->debug(
            'User ' . $self->{'user'}->username() . ' is already logged in' );

        return $self->redirect_ok(
            'Вход в систему уже выполнен', 'welcome' );
    }

    my $username = $self->{'params'}{'username'};
    my $password = $self->{'params'}{'password'};

    if ( $ENV{'REQUEST_METHOD'} eq 'GET' ) {
        return $self->process_template( 'login.tt2', {} );
    }

    $self->{'user'} = Meter::Users->retrieve(
        username => $username,
        password => $password,
    );

    if ( $self->{'user'} ) {
        eval { $self->create_session( $self->{'user'} ) };

        if ($EVAL_ERROR) {
            my $why = $EVAL_ERROR;
            $logger->error("Cannot create session: $why");

            return $self->redirect_error(
                'Ошибка создания сессии',
                'login', $why );

        }

        $logger->info( 'User '
                . $self->{'user'}->username()
                . ' has successfully logged in' );

        return $self->redirect_ok(
            'Вход в систему успешно выполнен',
            'welcome' );
    }
    else {
        $logger->warn("User '$username' login failed");

        return $self->redirect_error(
            'Нет такого пользователя либо неправильный пароль',
            'login'
        );
    }
}

sub create_session {
    my $self = shift;
    my $user = shift;

    my $logger     = get_logger();
    my $session_id = generate_session_id();
    my $cookie     = $self->{'cgi'}->cookie(
        -name    => 'SessionID',
        -value   => $session_id,
        -expires => $self->{'config'}{'session_cookie_expires'},
    );

    $self->set_header( -cookie => [$cookie] );

    $self->{'session'} = Meter::Sessions->insert(
        {   session_id             => $session_id,
            user                   => $user,
            last_activity_datetime => $self->now(),
        }
    );

    $logger->info( "Session '$session_id' for user "
            . $user->username()
            . ' has been successfully created' );

    return;
}

sub get_error_regexes_list {
    my $self = shift;

    return [
        {   regex => qr/\Qsession_id fails 'regexp' constraint\E/xms,
            message =>
                'идентификатор сессии имеет неправильный формат'
        },
    ];
}

1;
